<?php
/**
 * @link http://www.tintsoft.com/
 * @copyright Copyright (c) 2013 TintSoft LLC
 * @license http://www.tintsoft.com/license/
 */
namespace Leaps\Base;
use Leaps;
use Leaps\Base\Contracts\ArrayableInterface;
/**
 * 通用异常类
 *
 * @author Tongle Xu <xutongle@gmail.com>
 * @since 4.0
 */
class Exception extends \Exception implements ArrayableInterface
{
	/**
	 * 返回异常的用户友好名称
	 *
	 * @return string
	 */
	public function getName()
	{
		return Leaps::t ( 'leaps', 'Exception' );
	}

	/**
	 * 返回该对象的数组表示。
	 *
	 * @return array
	 */
	public function toArray()
	{
		return $this->toArrayRecursive ( $this );
	}

	/**
	 * 使用数组递归表示异常和前面的所有异常
	 *
	 * @param \Exception 异常对象
	 * @return array 数组表示的异常
	 */
	protected function toArrayRecursive($exception)
	{
		$array = [
			'type' => get_class ( $exception ),
			'name' => $exception instanceof self ? $exception->getName () : 'Exception',
			'message' => $exception->getMessage (),
			'code' => $exception->getCode ()
		];
		if (($prev = $exception->getPrevious ()) !== null) {
			$array [ 'previous' ] = $this->toArrayRecursive ( $prev );
		}
		return $array;
	}
}
